package com.tengju.bff.interfaces.manage.club.facade;

import com.google.common.collect.Lists;
import com.tengju.bff.interfaces.manage.club.assembler.ZoneAssembler;
import com.tengju.bff.interfaces.manage.club.vo.PageZoneInfoVO;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.KVVO;
import com.tengju.user.application.archives.dto.PageQueryDTO;
import com.tengju.user.application.club.ZoneService;
import com.tengju.user.domain.model.club.*;
import com.tengju.user.domain.model.user.UserIdCode;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ZoneFacade {

    @Autowired
    private ZoneService zoneService;

    @Autowired
    private ZoneRepository zoneRepository;

    private final UserZoneMemberRepository userZoneMemberRepository;

    public PageZoneInfoVO queryByPage(PageQueryDTO pageQueryDTO) {

        Integer total = zoneRepository.count();
        Integer pageSize = pageQueryDTO.getPageSize();
        Integer pageIndex = pageQueryDTO.getPageIndex();
        Integer offset = (pageIndex - 1) * pageSize;

        List<Zone> zoneList = Lists.newArrayList();
        if (offset <= total) {
            zoneList = zoneService.queryByPage(pageQueryDTO);
        }


        return ZoneAssembler.ModelToVO(zoneList,pageQueryDTO,total);

    }

    public List<KVVO> getUserZoneMemberInfo(ZoneId zoneId) {

        List<UserIdCode> userIdCodeList = userZoneMemberRepository.selectIdcodeByZoneId(zoneId);

        // secId逗号拼接返回
        String secIds = "";
        if (CollectionUtils.isNotEmpty(userIdCodeList)) {
            secIds = userIdCodeList.stream()
                    .filter(Objects::nonNull)
                    .map(UserIdCode::getValue)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
        }

        List<KVVO> header = List.of(
                KVVO.of("设置SEC", secIds)
        );

        return header;
    }
}
